#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <pthread.h>

#include "worker.h"
#include "queue.h"

static queue_t *queue = NULL;
static int type0 = 0;
static int type1 = 1;

void thread_func1(worker_t *worker, void *arg)
{
    int cnt = 0;
    int worker_id = *((int *)arg);
    work_task_t *task = NULL;

    if (arg == NULL) {
        return;
    }
    // printf("start thread: %d\n", worker_id);
    for (int i = 0; i < 11; i++) {
        // sleep(1);
        task = queue_alloc_data(queue);
        if (task == NULL) {
            printf("alloc data error\n");
            continue;
        }
        task->data = i;
        queue_put(queue, task);
        // printf("thread %d push data: %lu %d\n", worker_id, task->task_id, task->data);
        cnt++;
    }
    printf("stop thread: %d %d\n", worker_id, cnt);
}

void thread_func2(worker_t *worker, void *arg)
{
    int cnt = 0;
    int worker_id = *((int *)arg);
    work_task_t *task = NULL;
    if (arg == NULL) {
        return;
    }

    // printf("start thread: %d\n", worker_id);
    for (int i = 0; i < 11; i++) {
        // sleep(1);
        task = queue_take(queue);
        if (task == NULL) {
            printf("take data error\n");
            continue;
        }
        // printf("thread %d pop data: %lu %d\n", worker_id, task->task_id, task->data);
        queue_free_task(queue, task);
        cnt++;
    }
    printf("stop thread: %d %d\n", worker_id, cnt);
    return;
}

void run_test(void)
{
    worker_t *worker = NULL;
    for (int i = 1; i < 7; i++) {
        if (i%2 == 1) {
            worker = worker_create(&type0, thread_func1);
            // printf("create worker type 0: %d %p\n", i, worker);
        } else {
            worker = worker_create(&type1, thread_func2);
            // printf("create worker type 1: %d %p\n", i, worker);
        }
    }
}

int main(void)
{
    queue = queue_create(1024);
    run_test();
    sleep(10);
    printf("main exit\n");
    queue_destory(queue);
    return 0;
}
